#!/usr/bin/perl

# ---------- Init variables -------
#my $version = "0.0001";
# ---------- external readable parameters -------
## Functions
##-------------------------------------------------------
#
# stict syntax checking.
use strict;
use CGI qw(param);
use SIM_settings;
use SIM_base;

# Startupscript casetool, part of Sipman.

my $module = $ARGV[0];
my $tool = $ARGV[1];
my $action = $ARGV[2];
my $option1 = $ARGV[3];
my $option2 = $ARGV[4];
my $option3 = $ARGV[5];


my $backHeader="black";
my $httpUser = $ENV{'REMOTE_USER'};
my $httpReF = $ENV{'HTTP_REFERER'};
my $httpScriptName = $ENV{'SCRIPT_NAME'};
my $httpUserIp = $ENV{'REMOTE_ADDR'};
my $httpServerName = $ENV{'HTTP_HOST'};
my $httpCookie = $ENV{'HTTP_COOKIE'};
my $httpHost = $ENV{'HTTP_HOST'};
my $updateTool = $ENV{'SIM_UPDATET'} || die "No env SIM_UPDATET found.";
my $upgradeTool = $ENV{'SIM_UPGRADES'} || die "No env SIM_UPGRADES found.";
my $tmpDir = $ENV{'SIM_TMPDIR'} || die "No env SIM_TMPDIR found.";
my $baseDir = $ENV{'SIM_BASEDIR'} || die "No env SIM_BASEDIR found.";
my @deviceTypes = qw( net srv win ux fix wks );
my $sourcesFile = "$tmpDir/sipmanSources.txt";


sub printMainMenu {
  my $fontColor = "#222222";
  print("<TABLE WIDTH=100% BORDER=0 CELLSPACING=0><TR><TD BGCOLOR=#EEEEEE><CENTER>
    <A HREF=$httpScriptName?$module+$tool+reboot><FONT COLOR=$fontColor>Reboot</FONT></A> |
    <A HREF=$httpScriptName?$module+$tool+backupSipman><FONT COLOR=$fontColor>Backup Sipman</FONT></A> 
    <FONT COLOR=#666666>Upgrade</FONT>
    <A HREF=$httpScriptName?$module+$tool+upgradeSipman><FONT COLOR=$fontColor>Sipman</FONT></A> |
    <A HREF=$httpScriptName?$module+$tool+upgradeDebian><FONT COLOR=$fontColor>Debian</FONT></A> /
    <A HREF=$httpScriptName?$module+$tool+repair-Debian><FONT COLOR=$fontColor>repair</FONT></A> 
    </TD></TR></TABLE><CENTER>
        ");
}
sub refreshSourcesList {
  if ( -f $sourcesFile ) {
    unlink $sourcesFile;
  }
  print("<TABLE><TR><TD><PRE>");
  system(" wget --output-document=$sourcesFile http://www.sipman.net/downloads/sources/sourcesList.txt ");
  print("</PRE></TD></TR></TABLE><HR>");
  &upgradeSipman;
}

sub upgradeSipman {
  my $versionInfo = catFileLine("$SIMparam{'SIMmainConfigDir'}/version.txt");
  print("<BR><B><FONT SIZE=+2>Upgrading tool.</FONT></B> (Current version $versionInfo)<P>
    Select <A HREF=$httpScriptName?$module+$tool+refreshSourcesList>refresh</A> to get an fresh sources list.<HR>");
  my $uploadfile = param('uploadfile');
  if ( "$uploadfile" eq "" ) {
    print("<TABLE><TR><TD><PRE>");
    system(" wget --output-document=$sourcesFile http://www.sipman.net/downloads/sources/sourcesList.txt ");
    print ("</PRE></TD></TR></TABLE><HR><CENTER>
      <FORM ACTION=$httpScriptName?$module+$tool+upgradeSipman METHOD=post ENCTYPE=multipart/form-data>
        <TABLE>
  	  <TR><TD>
	    File to Upload:
	  </TD><TD>
	    <SELECT NAME=uploadfile SIZE=1>");
    if ( open(FH, $sourcesFile)) {
      my @lines = reverse <FH>;
      close FH;
      foreach my $regel (@lines) {
        chomp $regel;
        my $end = substr( $regel, -8 );
	if ( "$end" eq "main.tgz" ) {
          print("<OPTION VALUE=$regel>$regel</OPTION>");
	}
      }
    }
    print("</SELECT>
	  </TD></TR>
	</TABLE>
	<INPUT TYPE=\"submit\" NAME=\"Submit\" VALUE=\"Start upgrade.\">
      </FORM>
	  ");
  } else {
    my $outFile = "$tmpDir/$uploadfile";
    if ( -f $outFile ) {
      unlink $outFile;
    }
    print("<TABLE><TR><TD><PRE><B>Getting $uploadfile.</B><HR>");
    system(" wget --output-document=$outFile http://www.sipman.net/downloads/sources/$uploadfile");
    chdir("/var/tmp");
    print("<B>Unpacking source.</B><HR>");
    system(" tar -zxvf $outFile ");
    if ( -f "main/configs/version.txt" ) {
      print("<P><B>Code seems oke, starting upgrade.</B><HR>
      Running $upgradeTool as root.");
      system(" $sipmanStarter upgrade-Sipman $manDomain verbose ");
    }
    if ( -d "/var/tmp/main" ) {
      print("<P><B>Oops, the main directory still exists, removing it.</B><HR>");
      system(" rm -vfR /var/tmp/main ");
    }
    print("</PRE></TD></TR></TABLE>");
  }
}

sub upgradeDebian {
  print("</CENTER><PRE>");
  print("<H3>Getting package release info</H3>");
  system(" sudo apt-get update ");
  print("<H3>Upgrading Debian</H3>");
  system(" sudo apt-get -y upgrade ");
  print("</PRE>");
}

sub backupSipman {
  print("Removing old backups....<BR>");
  my $workDir = $SIMparam{'SIMsystemHtmlDir'};
  my $random = $$;
  if ( -d $workDir ) {
    system(" rm -fR $workDir/backup-* ");
  }
  print("Creating backup:<HR><PRE>");
  if ( mkdir "$workDir/backup-$random" ) {
    my $now = time;
    my $date = printDate($now, "yyyymmdd");
    my $outFile = "/var/tmp/sipman-$date.tgz";
    printDebug(0, "outFile=$outFile");
    system(" tar -zcf $outFile $SIMparam{'SIMbaseDir'} ");
    system(" mv -v $outFile $workDir/backup-$random ");
    print("<HR>Download <A HREF=/sipman-system/backup-$random/sipman-$date.tgz>sipman-$date.tgz</A>.");
  }
  
}

# ------------------------------------- Main ---------------------------------------

&printMainMenu;
if ( "$action" eq "backupSipman" ) {
  backupSipman;
} elsif ( "$action" eq "upgradeSipman" ) {
  upgradeSipman;
} elsif ( "$action" eq "upgradeDebian" ) {
  system(" $sipmanStarter upgrade-Debian $manDomain verbose ");
} elsif ( "$action" eq "repair-Debian" ) {
  system(" $sipmanStarter repair-Debian $manDomain verbose ");
} elsif ( "$action" eq "refreshSourcesList" ) {
  refreshSourcesList;
} elsif ( "$action" eq "reboot" ) {
  system(" $sipmanStarter reboot-system $manDomain verbose ");
} else {
  print("Select an option from the above menu.");
}
#&printFooter;
